package cn.harry.cabinet.server.routes

import cn.harry.cabinet.model.entity.Configuration
import cn.harry.cabinet.repository.ConfigurationRepository
import cn.harry.cabinet.server.dto.common.ApiResponse
import cn.harry.cabinet.server.dto.config.ConfigurationResponse
import cn.harry.cabinet.server.dto.config.ConfigurationUpdateRequest
import io.ktor.http.HttpStatusCode
import io.ktor.server.application.call
import io.ktor.server.request.receive
import io.ktor.server.response.respond
import io.ktor.server.routing.Route
import io.ktor.server.routing.get
import io.ktor.server.routing.put
import io.ktor.server.routing.route
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import kotlinx.serialization.InternalSerializationApi

@OptIn(InternalSerializationApi::class)
fun Route.configurationRoutes(configurationRepository: ConfigurationRepository) {

	route("/api/configurations") {

		// 获取所有配置或按type过滤
		get {
			try {
				val type = call.request.queryParameters["type"]
				withContext(Dispatchers.IO) {
					val list = if (type.isNullOrBlank()) configurationRepository.getAll() else configurationRepository.getByType(type)
					call.respond(HttpStatusCode.OK, ApiResponse.success(ConfigurationResponse.fromList(list), "获取配置列表成功"))
				}
			} catch (e: Exception) {
				call.respond(HttpStatusCode.InternalServerError, ApiResponse.errorResponse(500, "获取配置列表失败: ${e.message}"))
			}
		}

		// 通过type和key获取配置
		get("/by-key") {
			try {
				val type = call.request.queryParameters["type"]
				val key = call.request.queryParameters["key"]
				if (type.isNullOrBlank() || key.isNullOrBlank()) {
					call.respond(HttpStatusCode.BadRequest, ApiResponse.errorResponse(400, "type和key不能为空"))
					return@get
				}
				withContext(Dispatchers.IO) {
					val config = configurationRepository.getByTypeAndKey(type, key)
					if (config == null) {
						call.respond(HttpStatusCode.NotFound, ApiResponse.errorResponse(404, "配置不存在"))
					} else {
						call.respond(HttpStatusCode.OK, ApiResponse.success(ConfigurationResponse.from(config), "获取配置成功"))
					}
				}
			} catch (e: Exception) {
				call.respond(HttpStatusCode.InternalServerError, ApiResponse.errorResponse(500, "获取配置失败: ${e.message}"))
			}
		}

		// 通过type和key更新配置
		put("/by-key") {
			try {
				val type = call.request.queryParameters["type"]
				val key = call.request.queryParameters["key"]
				val t = type?.trim() ?: ""
				val k = key?.trim() ?: ""
				if (t.isEmpty() || k.isEmpty()) {
					call.respond(HttpStatusCode.BadRequest, ApiResponse.errorResponse(400, "type和key不能为空"))
					return@put
				}
				val req = call.receive<ConfigurationUpdateRequest>()
				withContext(Dispatchers.IO) {
					val existing = configurationRepository.getByTypeAndKey(t, k)
					if (existing == null) {
						// 不存在则创建
						val created = configurationRepository.create(Configuration(type = t, key = k, value = req.value))
						call.respond(HttpStatusCode.Created, ApiResponse.success(ConfigurationResponse.from(created), "创建配置成功"))
					} else {
						val updated = existing.copy(value = req.value, updateTime = java.util.Date())
						configurationRepository.update(updated)
						call.respond(HttpStatusCode.OK, ApiResponse.success(ConfigurationResponse.from(updated), "更新配置成功"))
					}
				}
			} catch (e: Exception) {
				call.respond(HttpStatusCode.InternalServerError, ApiResponse.errorResponse(500, "更新配置失败: ${e.message}"))
			}
		}
	}
}

